package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        Long attrGroupId = attr.getAttrGroupId();
        if (attrGroupId!=null && attrGroupId!=0){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        String key = (String) params.get("key");
            LambdaQueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().lambda();
        wrapper.eq(catelogId != 0, AttrEntity::getCatelogId, catelogId).eq(AttrEntity::getAttrType,"base".equalsIgnoreCase(type)? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() :ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        System.out.println(catelogId);
        wrapper.and(!StringUtils.isBlank(key),wapper->{
            wapper.eq(AttrEntity::getAttrId,key).or().like(AttrEntity::getAttrName,key);
        });
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),wrapper
        );
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> respVos = records.stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            if ("base".equalsIgnoreCase(type)){
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId()));
                if (relationEntity!=null) {
                    AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            if (attrEntity.getCatelogId()!=null){
                Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
                String path = "";
                for (int i = 0; i < catelogPath.length; i++) {
                    CategoryEntity byId = categoryService.getById(catelogPath[i]);
                    if (i==catelogPath.length-1){
                        path += byId.getName();
                        break;
                    }
                    path += byId.getName()+"/";
                }
                attrRespVo.setCatelogName(path);

            }

            return attrRespVo;
        }).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(respVos);
        return pageUtils;
    }
    @Cacheable(value = "attr",key = "'attrinfo:'+#root.args[0]")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity byId = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(byId,attrRespVo);
        AttrAttrgroupRelationEntity attrgroupRelation = attrAttrgroupRelationService.getOne(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId, attrId));
       if (attrgroupRelation!=null){
           attrRespVo.setAttrGroupId(attrgroupRelation.getAttrGroupId());
           AttrGroupEntity attrGroup = attrGroupService.getById(attrgroupRelation.getAttrGroupId());
           if (attrGroup!=null){
               attrRespVo.setGroupName(attrGroup.getAttrGroupName());
           }
       }
        Long[] catelogPath = categoryService.findCatelogPath(byId.getCatelogId());
        attrRespVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryService.getById(byId.getCatelogId());
        if (categoryEntity!=null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }
    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);
        if (attr.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());
            int count = attrAttrgroupRelationService.count(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId, relationEntity.getAttrId()));
            if (count>0){
                attrAttrgroupRelationService.update(relationEntity,new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId,relationEntity.getAttrId()));
            }else {
                attrAttrgroupRelationService.save(relationEntity);
            }
        }
    }

    @Override
    public void removeByIdsAndGroup(List<Long> asList) {
        this.removeByIds(asList);
        Map<String,Object> map=new HashMap<>();
        for (Long id:asList){
            map.put("attr_id",id);
        }
            attrAttrgroupRelationService.removeByMap(map);
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> list = attrAttrgroupRelationService.list(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrgroupId));
        List<Long> longList = list.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        List<AttrEntity> attrEntities = new ArrayList<>();
        if (longList!=null&&longList.size()!=0){
            attrEntities = (List<AttrEntity>) this.listByIds(longList);
            return attrEntities;
        }
        return attrEntities;
    }
    @Transactional
    @Override
    public PageUtils getNoRelationAttr(Long attrgroupId, Map<String, Object> params) {
        AttrGroupEntity attrGroup = attrGroupService.getOne(new LambdaQueryWrapper<AttrGroupEntity>().eq(AttrGroupEntity::getAttrGroupId, attrgroupId));
        Long catelogId = attrGroup.getCatelogId();
        List<AttrGroupEntity> list = attrGroupService.list(new LambdaQueryWrapper<AttrGroupEntity>().eq(AttrGroupEntity::getCatelogId,catelogId));//.ne(AttrGroupEntity::getAttrGroupId,attrgroupId)
        List<Long> groupIds = list.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
        List<AttrAttrgroupRelationEntity> list1 = attrAttrgroupRelationService.list(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().in(AttrAttrgroupRelationEntity::getAttrGroupId, groupIds));
        List<Long> attrIds = list1.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        String key = (String) params.get("key");
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>().lambda().notIn(attrIds!=null&&attrIds.size()!=0,AttrEntity::getAttrId,attrIds).eq(AttrEntity::getCatelogId,catelogId).eq(AttrEntity::getAttrType,ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()).and(!StringUtils.isEmpty(key),wapper->{
                    wapper.eq(AttrEntity::getAttrId,key).or().like(AttrEntity::getAttrName,key);
                })
        );
        return new PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrsIds(List<Long> attrIds) {
        List<AttrEntity> list = this.list(new LambdaQueryWrapper<AttrEntity>().in(AttrEntity::getAttrId,attrIds).eq(AttrEntity::getSearchType, 1));
        List<Long> collect = list.stream().map(attr -> attr.getAttrId()).collect(Collectors.toList());
        return collect;
    }
}